<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%@ taglib prefix="sys" uri="/WEB-INF/tld/sys.tld" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>自主认款列表 管理</title>
    <style type="text/css">
    </style>
    <jsp:include page="../../import.jsp" flush="true"/>
</head>

<body class="iframeBody">
<div class="Wrapper">
    <div class="searchArea">
        <form id="searchBar">
            <div class="fieldset1 clearFix">
                <div class="fieldBox ">
                    <div class="label">来款户名</div>
                    <div class="field">
                     <input name="comeNameAlias" id="comeNameAlias" type="text" class="ui-textbox" value="" validate="{required:true}" onclick="onCheckUp()"  >
                       <!--  <input name="comeNameAlias" id="comeNameAlias" type="text" class="ui-textbox" value="" validate="{required:true}"> -->
                    </div>
                </div>
                <div class="fieldBox ">
                    <div class="label">资金类型</div>
                    <div class="field">
                        <select name="capTypCd" id="capTypCd" data-value=" ">
                            <option value=" " checked>请选择</option>
                            <c:forEach items="${fundConfirmByListPage}" var="kv">
                                <option value="${kv.key}">${kv.value}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
                <div class="fieldBox">
                    <div class="label">来款金额</div>
                    <div class="field">
                    <!-- <input name="amount" id="amount" type="text" class="ui-textbox" onchange="Num(this)" value="" validate="{required:true,number:true}"> -->
                        <input name="amount" id="amount" type="text" class="ui-textbox" onchange="Num(this)" value="" validate="{required:true,number:true}" onclick="onCheckUp()"  >
                    </div>
                </div>
                <div class="fieldBox">
                    <div class="label">到账日期</div>
                    <div class="field">
                        <input ligerui="width: 82" name="acceptDateMin" id="acceptDateMin" type="text"
                               class="ui-datepicker" value="" validate="{required:true}" onclick="onCheckUp()" >
                        -
                        <input ligerui="width: 82" name="acceptDateMax" id="acceptDateMax" type="text"
                               class="ui-datepicker" value="" validate="{required:true}" onclick="onCheckUp()" >
                    </div>
                </div>
                <div class="fieldBox">
                    <div class="label">收款账号</div>
                    <div class="field">
                        <input name="acceptCode" id="acceptCode" type="text" class="ui-textbox" value="">
                    </div>
                </div>
                <%--<div class="fieldBox ">
                    <div class="label">来款账号</div>
                    <div class="field">
                        <input name="comeCodeAlias" id="comeCodeAlias" type="text" class="ui-textbox" validate="{required:false}">
                    </div>
                </div>--%>
                <div class="formBtns notRight">
                    <span id="searchBtn" class="sq-button sq-button-round"></i>查询</span>
                    <span id="clearBtn" class="sq-button sq-button-round"></i>清空</span>
                    <sys:funcAuth resCd="exportComFundList">
                        <span id="exportBtn" class="sq-button sq-button-round">导出</span>
                        <%--<span id="frozenBtn" class="sq-button sq-button-round">冻结</span>--%>
                        <span id="outBtn" class="sq-button sq-button-round">转出</span>
                    </sys:funcAuth>
                    <input id="resetBtn" type="reset" value="重置" class="l-button l-button-reset Hide"/>
                </div>
            </div>
        </form>
    </div>

    <div id="ligergrid1" class="sq-grid"></div>
    <%--<form id="capFund_type_form" style="display: none;">
        <div class="fieldset1 clearFix">
            <div class="fieldBox" id='cont_text_id'>
            </div>
          </div>
    </form>--%>
</div>

<script type="text/javascript">
    var grid = null, form = null;
    var callback = null;

    var roleNm = '${roleNm}';


    $(function () {
        //debugger; 拿到这个form 验证设置通过
        form = $("#searchBar").ligerForm({
            validate: true
        });
        //加载资金类型
        var fundConfirmByListPageListJSON = [];
        <c:if test="${not empty fundConfirmByListPageListJSON}">
        fundConfirmByListPageListJSON = ${fundConfirmByListPageListJSON};
        </c:if>

        var columns_hide = true;
        var columns_hide_SurpluOutAmt = true;
        var type_grid = '${type}';
        var capTypCdSelect='select'
        //已分解资金列表
        if (type_grid == 2) {
            columns_hide = false
           var capTypCdSelect='';
        }
        if (type_grid == 3) {
        	columns_hide_SurpluOutAmt = false
            var capTypCdSelect='';
        }
        
        grid = $("#ligergrid1").ligerGrid({
            url: '<%=path%>/capital/capFund/initList.do',
            // parms: {fundStatusCD: 0,type:type_grid},//列表加载 状态 传入  未分解0
            parms: {type: type_grid},//列表加载 状态 传入  未分解0
            method: 'get',
            columns: [
                {display: '资金编号', name: 'code', width: 130, align: 'center', enabledSort: false},
                {display: '资金状态', name: 'fundStatusCdNm', width: 60, align: 'center', enabledSort: false},
                {display: '收款账号', name: 'acceptCode', minWidth: 100, align: 'left', enabledSort: false},
                {display: '收款户名', name: 'acceptName', minWidth: 100, align: 'left', enabledSort: false},
                {display: '来款账号', name: 'comeCode', minWidth: 100, align: 'left', enabledSort: false},
                {display: '来款户名', name: 'comeName', minWidth: 100, align: 'left', enabledSort: false},
                {
                    display: '来款金额', name: 'amount', width: 100, align: 'right', enabledSort: false,
                    render: function (rowdata, index, value) {
                        return '&yen;' + FormatMoney(rowdata.amount / 100);
                    }
                },
                {
                    display: '剩余可转金额', name: 'surpluOutAmt', width: 100, align: 'right', hide: columns_hide_SurpluOutAmt,enabledSort: false,
                    render: function (rowdata, index, value) {
                    	//debugger;
                        return '&yen;' + FormatMoney(rowdata.surpluOutAmt / 100);
                    }
                },
                {
                    display: '摘要', name: 'docketRem', width: 130, align: 'left', enabledSort: false,
                    render: function (rowdata, index, value) {
                        if (value) {
                            var h = '<span class="gridTip" style="cursor: pointer;" title="' + rowdata.docketRem + '">' + rowdata.docketRem + '</span>';
                            return h;
                        }
                    }
                },
                {display: '客户名称', name: 'cstNm', minWidth: 100, align: 'center', enabledSort: false,},
                {
                    display: '到账日期',
                    name: 'acceptDate',
                    width: 130,
                    align: 'center',
                    enabledSort: false,
                    render: renderDate2
                },
                {display: '认款人', name: 'identifyOperatorNm', width: 100, align: 'center', enabledSort: false},
                {
                    display: '认款时间',
                    name: 'identifyTime',
                    width: 130,
                    align: 'center',
                    enabledSort: false,
                    render: renderDate
                },
                {
                    display: '分解时间',
                    name: 'decomposeTime',
                    width: 130,
                    align: 'center',
                    hide: columns_hide,
                    enabledSort: false,
                    render: renderDate
                },
                {
                    display: '资金类型', name: 'capTypCd', width: 150,
                    editor: {
                        type: capTypCdSelect,
                        data: fundConfirmByListPageListJSON,
                        valueField: 'key',
                        textField: 'value'
                    },
                    valueField: 'capTypCd',
                    textField: 'capTypCdNm',
                    render: function (item) {
                        if (StringUtils.isEmpty(item.capTypCd)) {
                            item.capTypCdNm = "请选择资金类型！";
                            return '请选择资金类型<i class="ico_flasher"></i>';
                        } else {
                            return item.capTypCdNm
                        }
                    }
                },
                {
                    display: '操作', name: '', minWidth: 150, align: 'left', enabledSort: false,
                    render: function (rowdata, index, value) {
                        var action = '';
                        if (rowdata.fundStatusCd == '0' || rowdata.fundStatusCd == '1') {
//                            if(rowdata.fundSourcesCd != null && rowdata.fundSourcesCd == '7'){
//
//                            }else{
//                                action += '<a class="sq-button-hasicon" href="javascript:confirmFund(' + rowdata.id + ',\'' + rowdata.comeCode + '\',\'' + rowdata.comeName + '\',\'' + rowdata.capTypCd + '\',\'' + rowdata.acceptDate + '\',\'' + rowdata.acceptName + '\');"><i class="sqBtnIco_2"></i>认款</a>';
//                            }

                            action += '<sys:funcAuth resCd="toFundConfirmPage">'+'<a class="sq-button-hasicon" href="javascript:confirmFund(' + rowdata.id + ',\'' + rowdata.comeCode + '\',\'' + rowdata.comeName + '\',\'' + rowdata.capTypCd + '\',\'' + rowdata.acceptDate + '\',\'' + rowdata.acceptName + '\');"><i class="sqBtnIco_2"></i>认款</a>'
                                +'</sys:funcAuth>';
                        }
                        action += '<a class="sq-button-hasicon" href="javascript:remarkFund(' + rowdata.id + ',\'' + rowdata.comeName + '\');"><i class="sqBtnIco_4"></i>添加备注</a>';
                        return action;
                    }
                },
            ],
            onBeforeEdit: function (e) {
                /* debugger;
                 //编辑前事件[点击选择框后加载]
                 if(e.column.name=="capTypCd"){
                 //通过判断是否是这一列  然后把这一行得到的数据赋值到这个编辑器
                 e.column.editor.data = e.record.capFunTypeList;
                 }*/
            },
            onBeforeSubmitEdit: function (e) {
                //验证编辑器结果是否通过 [介于编辑后未提交之前  原始数据与新数据对比]
                if (e.column.name == "capTypCd") {
                    //原始值与选中值判断是否一致
                    //debugger;
                    if (StringUtils.isEmpty(e.value) || e.record.capTypCd == e.value) {
                        $.ligerDialog.SQalert({content: LogUtils.LOG_CAP_FUND_TYPE_LOG, SQ_type: "warning"});
                    } else {
                        onModify(e.record.id, e.value);
                    }
                }
            },
            enabledEdit: true,
            pageSize: 10,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: '100%',
            heightDiff: -2,
            checkbox: true,
            rownumbers: true,
            usePager: true,//
            isScroll: true,//要不要滚动条
            allowUnSelectRow: true,
            alternatingRow: true,//
            delayLoad: true, //需延时加载
            allowHideColumn: false//设置他的列不可选择
        });


        $("#pageloading").hide();
        var type = '${type}';//查询类型 认款记录
        if (type == '2') {
            grid.removeParm('fundStatusCD');
            grid.setParm('fundStatusCD', "2");//已分解
            grid.setParm('identifyOperator', '${operator}');
            grid.reload();
            form.setFieldValidate("comeNameAlias", {required: false});
            form.setFieldValidate("amount", {required: false});
            //$("#frozenBtn").hide();//冻结
            $("#outBtn").hide();//转出
        } else if (type == '3') {
            grid.removeParm('fundStatusCD');
            grid.setParm('fundStatusCD', null);//已分解
            grid.setParm('identifyOperator', '${operator}');//?后台列表拿不到吗？
            grid.reload();
            form.setFieldValidate("comeNameAlias", {required: false});
            form.setFieldValidate("amount", {required: false});

            //$("#exportBtn").hide();//导出
            //$("#frozenBtn").hide();//冻结
        } else if (type == '1') {
            $("#outBtn").hide();//转出
            // 带有确定按钮
                $.ligerDialog.SQalert({
                	type:'warn' ,
                    SQ_showButtons: true,
                    SQ_onBtnclick: function (item, Dialog) {
                        console.log(item, Dialog);
                    },
                    content:'<span  style="color:red" >'+LogUtils.LOG_CAP_FUND_RENK+' </span>'
           });
        }

        /* 查询 */
        $("#searchBtn").click(function (event) {
            if (!form.valid()) {
                $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO, SQ_type: "warning"});
                return false; //验证不通过，不执行以下代码
            }

            var data = form.getData();
            for (name in data) {
                grid.setParm(name, data[name]);
            }
            grid.reload();

        });

        /* 清空 */
        $("#clearBtn").click(function (event) {
            $("#resetBtn").click();  //重置 input-text
            //清空后查不出数据的情况
            var form = liger.get("searchBar");
            form.setData({  //重置select等特殊表单
                "capTypCd": " "
            });
            
            /* form.setFieldValidate("comeNameAlias", {required: false});
            form.setFieldValidate("amount", {required: false});
            
            form.setFieldValidate("acceptDateMin", {required: false});
            form.setFieldValidate("acceptDateMax", {required: false}); */
            
        });

        //自定义函数加载表格
        callback = function () {
            grid.reload();
        };

        //导出待认款以及分解中及已分解
        $("#exportBtn").click(function (event) {
            var form = liger.get("searchBar");
            var data = form.getData();
            data['type'] = '${type}';
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: '<%=path%>/capital/capFund/exportFundList.do',
                data: data,
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: '正在导出...', SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        window.open(msg.data);
                    } else {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });

        });

        //财务权限
        if ($("#exportBtn").length > 0) {
            form.setFieldValidate("comeNameAlias", {required: false});
            form.setFieldValidate("amount", {required: false});
            
            form.setFieldValidate("acceptDateMin", {required: false});
            form.setFieldValidate("acceptDateMax", {required: false});
        }
        //加载资金类型数据
        //onFundType();
    });


    //认款
    function confirmFund(id, comeCode, comeName, capTypCd, acceptDate,acceptName) {
        if (acceptName.indexOf("车正资产评估")!=-1) {
            $.ligerDialog.SQalert({content: "车正到款不允许认款和分解", SQ_type: "warning"});
            return; //验证不通过，不执行以下代码
        }
        if ((StringUtils.isEmpty(capTypCd))) {
            $.ligerDialog.SQalert({content: LogUtils.LOG_CAP_FUND_TYPE_ISCHECK_LOG, SQ_type: "warning"});
            return; //验证不通过，不执行以下代码
        }
        //到账后15天后，资金可以查到，不支持认款，不支持分解，
        if ((StringUtils.isEmpty(acceptDate))||(parseInt(new Date()-acceptDate)/1000/60/60/24)>15) {
            $.ligerDialog.SQalert({content: "资金到账时间超过15天，不支持认款及分解操作，请走汇款到账查询流程进行处理。", SQ_showButtons: true, SQ_type: "error"});
            return; //验证不通过，不执行以下代码
        }
        
        //同一打款人第16天打来第二笔资金，系统提示有历史资金未使用，不支持新资金认款分解；
        <%-- $.ajax({
        	type: 'post',
            dataType: 'json',
            async: false,
            url: '<%=path%>/capital/capFund/getCapFundForSameAccept.do',
            data: {
            	"comeCode": comeCode,
            	"comeName":	comeName,
            	"acceptDate": acceptDate
            },
            success:function(msg){
            	if (msg.success != 1) {
            		$.ligerDialog.SQalert({content: msg.info, SQ_showButtons: true, SQ_type: "error"});
            		return false;
                } else {
                	
                }
            },
            
        }); --%>
        
        var onFundConfirm = function (item, Dialog) {
            if (Dialog.onFundConfirm) Dialog.onFundConfirm();
        };
        var onFundDecompose = function (item, Dialog) {
            if (Dialog.onFundDecompose) Dialog.onFundDecompose();
        };
        
        $.ligerDialog.SQopen({
            cls: 'noBorder_Dialog',
            width: 950,
            height: 450,
            title: '认款列表',
            url: '<%=path%>/capital/capFund/toFundConfirmPage.do?opTyp=2&id=' + id + '&cstNm=' + comeName,
            // 自定义buttons的时候 不要设置 fixButtons: true
            buttons: [{
                text: "确认认款", onclick: onFundConfirm, type: 'ok', cls: 'l-dialog-btn-ok'
            }, {
                text: "确认认款且自动核销", onclick: onFundDecompose, type: 'ok', cls: 'l-dialog-btn-ok'
            }]
        });
        
        /*$.ligerDialog.open({
         width: 750,
         height: 500,
         title: '认款列表',
         url: '<%=path%>/capital/capFund/toFundConfirmPage.do?id=' + id + '&vfFlag=1&cstNm=' + comeName
         });*/
    }

    function updateFund(_id) {
        $.ligerDialog.open({
            width: 750,
            height: 400,
            title: '资金修改',
            url: '<%=path%>/capital/capFund/toModifyPage.do?id=' + _id + '&remFlag=1'
        });
    }

    //格式化时间
    function renderDate(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
        }
        return dateStr;
    }
    //选择查询时触发
     function onCheckUp() {
    	 form.setFieldValidate("comeNameAlias", {required: true});
         form.setFieldValidate("amount", {required: true});
         
         form.setFieldValidate("acceptDateMin", {required: true});
         form.setFieldValidate("acceptDateMax", {required: true});
    }
    
    
    
    //格式化时间
    function renderDate2(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
        }
        return dateStr;
    }

    //允许输入数字和小数点
    function Num(obj) {
        obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
        obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
        obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    }
    //备注
    function remarkFund(id, name) {
      //提示信息  正在查询 请稍后
      /*   var wait_dialog = UIUtils.alertWaiting(LogUtils.LOG_CMM_DATA_LOADING, function () {
        });  */
        var params = "id=" + id;
        
        /* Add_navTab('rem_log_ui' + id, '客户【' + name + '】来款备注 ', '<%=path%>/capital/capFundRemLog/toListPage.do?' + params, callback); 
        wait_dialog.close(); */
   	 $.ligerDialog.SQopen({
           cls: 'no_Modify_Fund_Rem',
           width: 850,
           height: 450,
           title: '添加资金转出记录',
           url:'<%=path%>/capital/capFundRemLog/toListPage.do?' + params
       });
    }

    //修改类型
    function onModify(id, value) {
        //如果客户恶意选中 这里将拦截
        if (StringUtils.isEmpty(value)) {
            $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_OPERATE_FAIL, SQ_type: "error"});
        }
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: '<%=path%>/capital/capFund/modifyFundType.do?id=' + id + '&value=' + value,
            success: function (msg) {
                if (msg.success == 1) {
                    $.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                    grid.reload($('.pcontrol input', grid.toolbar).val());//加载到当前页
                } else {
                    $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                }
            }
        });
    }
    
    //资金冻结
    $("#frozenBtn").click(function (event) {
    	//debugger;
        var selectedRows = grid.getSelectedRows();
        if (selectedRows.length == 0) {
            $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_MORE_ROW, SQ_type: "warning"});
            return;
        }
        var _ids = [];
        var _notDoneIds = [];
        for (var index in selectedRows) {
            if(selectedRows[index].fundSourcesCd != null && selectedRows[index].fundSourcesCd == '7'){
                _notDoneIds.push(selectedRows[index].id);
            }else{
                _ids.push(selectedRows[index].id);
            }
        }
        if(_ids.length == 0){
            $.ligerDialog.SQalert({content: LogUtils.LOG_CAP_FUND_SOURCE_LOG, SQ_type: "warning"});
            return ;
        }
        $.ligerDialog.confirm("是否冻结选中的资金?", function (flag) {
            if (flag == false)return;
            var wait_dialog;
            $.ajax({
                type: 'GET',
                dataType: 'json',
                data: {ids: JSON.stringify(_ids)},
                url: '<%=path%>/capital/capFund/modifyFundFreeze.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    if (msg.success == 1) {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                        grid.reload($('.pcontrol input', grid.toolbar).val());//加载到当前页
                        wait_dialog.close();
                    } else {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        });
    });

    
    // 资金转出
    $("#outBtn").click(function (event) {
    	 //debugger;
  	     var selectedRows = grid.getSelectedRows();
          if (selectedRows.length == 0) {
              $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_MORE_ROW, SQ_type: "warning"});
              return;
          }
          if (selectedRows.length >=2) {
              $.ligerDialog.SQalert({content: "目前不支持多选转出", SQ_type: "warning"});
              return;
          }
          if(selectedRows[0].fundSourcesCd != null && selectedRows[0].fundSourcesCd == '7'){
              $.ligerDialog.SQalert({content: LogUtils.LOG_CAP_FUND_SOURCE_LOG, SQ_type: "warning"});
              return ;
          }
         var _ids=selectedRows[0].id;
         var _ids_amt=selectedRows[0].amount;
           
  	     var onModifyFundFrozen = function (item, Dialog) {
  	     if (Dialog.onModifyFundFrozen) Dialog.onModifyFundFrozen();
  	    	 grid.reload($('.pcontrol input', grid.toolbar).val());//加载到当前页
  	        };
  	        
  		 $.ligerDialog.SQopen({
  	            cls: 'no_Modify_Fund_type',
  	            width: 950,
  	            height: 350,
  	            title: '添加资金转出记录',
  	            url:'<%=path%>/capital/capFund/toFundConfirmFrozen.do?ids='+_ids+'&fundAmt='+_ids_amt,
  	            buttons: [{
  	                text: "确认转出", onclick: onModifyFundFrozen, type: 'ok', cls: 'l-dialog-btn-ok'
  	            }]
  	        });
    });

</script>

</body>
</html>
